﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using HttpWebAdapters;
using HttpWebAdapters.Adapters;
using Sherwood.Web;
using SolrNet;
using SolrNet.Exceptions;
using SolrNet.Impl;

namespace Sherwood.Content.SearchClient
{
    public class SearchConnection : SolrConnection
    {
        public SearchClientBase SearchClient { get; set; }

        public SearchConnection(SearchClientBase searchClient) 
            : base(searchClient.SearchServiceUrl, new HttpWebRequestFactory(searchClient))
        {
            SearchClient = searchClient;
        }

        private class HttpWebRequestFactory : IHttpWebRequestFactory
        {
            private readonly SearchClientBase _searchClient;

            public HttpWebRequestFactory(SearchClientBase searchClient)
            {
                _searchClient = searchClient;
            }

            public IHttpWebRequest Create(Uri url)
            {
                var preparedSearchUrl = _searchClient.GetPreparedSearchUrl(url.Query.Trim('?'));
                return new HttpWebRequestAdapter((HttpWebRequest) WebRequest.Create(preparedSearchUrl));
            }
        }
    }

}
